package com.xiaoyu.lanling.net;

import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.birbit.android.jobqueue.Job;
import com.birbit.android.jobqueue.Params;
import com.birbit.android.jobqueue.RetryConstraint;
import com.facebook.imagepipeline.common.BytesRange;
import com.facebook.imagepipeline.producers.NetworkFetcher;
import com.xiaoyu.lanling.media.image.OkHttpImagePipelineConfigFactory;
import com.xiaoyu.lanling.media.image.OkHttpNetworkFetcher;
import com.xiaoyu.net.queue.Priority;
import com.xiaoyu.net.queue.RequestQueue;

import okhttp3.CacheControl;
import okhttp3.Request;

public class FrescoImageRequestJob extends Job {

    final OkHttpNetworkFetcher.OkHttpNetworkFetchState mFetchState;
    final NetworkFetcher.Callback mCallback;

    private FrescoImageRequestJob(Params params, OkHttpNetworkFetcher.OkHttpNetworkFetchState fetchState, NetworkFetcher.Callback callback) {
        super(params);
        mFetchState = fetchState;
        mCallback = callback;
    }

    public static void create(OkHttpNetworkFetcher.OkHttpNetworkFetchState fetchState, NetworkFetcher.Callback callback) {
        Params params = new Params(Priority.LOW);
        params.requireNetwork();
        params.setPersistent(false);
        FrescoImageRequestJob job = new FrescoImageRequestJob(params, fetchState, callback);
        RequestQueue.getInstance().addJob(job);
    }

    @Override
    public void onAdded() {
    }

    @Override
    public void onRun() throws Throwable {
        try {

            final OkHttpNetworkFetcher.OkHttpNetworkFetchState fetchState = mFetchState;
            final NetworkFetcher.Callback callback = mCallback;

            final Uri uri = fetchState.getUri();

            try {
                final Request.Builder requestBuilder = new Request.Builder()
                        .cacheControl(new CacheControl.Builder().noStore().build())
                        .url(uri.toString())
                        .get();

                final BytesRange bytesRange = fetchState.getContext().getImageRequest().getBytesRange();
                if (bytesRange != null) {
                    requestBuilder.addHeader("Range", bytesRange.toHttpRangeHeaderValue());
                }

                OkHttpImagePipelineConfigFactory.getOkHttpNetworkFetcher().fetchWithRequest(fetchState, callback, requestBuilder.build());
            } catch (Exception e) {
                // handle error while creating the request
                callback.onFailure(e);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
    }

    @Override
    protected void onCancel(int i, @Nullable Throwable throwable) {
    }

    @Override
    protected RetryConstraint shouldReRunOnThrowable(@NonNull Throwable throwable, int i, int i1) {
        return null;
    }
}
